package com.hmall.search.listener;

import com.alibaba.fastjson.JSON;
import com.hmall.search.pojo.ItemDoc;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.naming.Name;
import java.io.IOException;

/**
 * 监听器
 */
@Service
public class ItemListener {

    @Autowired
    RestHighLevelClient client;

    /**
     * 同步item中添加和修改
     * @param msg
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.update.queue"),
            exchange = @Exchange(name = "item.direct"),
            key = "item.update"
    ))
    public void handleUpdateMessage(String msg) throws IOException {
        System.err.println("接收信息成功:"+msg);
        ItemDoc itemDoc= JSON.parseObject(msg,ItemDoc.class);
        IndexRequest request=new IndexRequest("hmall");
        request.id(itemDoc.getId().toString());
        request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
    }

    /**
     * 同步删除
     * @param id
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.delete.queue"),
            exchange = @Exchange(name = "item.direct"),
            key = "item.delete"
    ))
    public void handleDeleteMessage(String id) throws IOException {
        System.err.println("接收信息成功:"+id);
        DeleteRequest request=new DeleteRequest("hmall",id);
        client.delete(request,RequestOptions.DEFAULT);
    }
}
